#pragma once

#include <iostream>
#include <string>
#include <vector>
#include <queue>
#include "task.hpp"
#include "Lock.hpp"
#include "thread.hpp"

using namespace std;

static const int n = 5;
template <class T>
class ThreadPool
{
public:
    ThreadPool(int num = n) : _num(num), _threads(num)
    {
        pthread_mutex_init(&_mt, nullptr);
        pthread_cond_init(&_cd, nullptr);
    }

    pthread_mutex_t *getlock()
    {
        return &_mt;
    }

    void Lockqueue()
    {
        pthread_mutex_lock(&_mt);
    }

    void Unlockqueue()
    {
        pthread_mutex_unlock(&_mt);
    }

    void Threadwait()
    {
        pthread_cond_wait(&_cd, &_mt);
    }

    void Threadwakeup()
    {
        pthread_cond_signal(&_cd);
    }

    bool isEmpty()
    {
        return _tasks.empty();
    }

    T popTask()
    {
        T t = _tasks.front();
        _tasks.pop();
        return t;
    }

    // 静态不能访问类内私有成员，所以传入this指针
    static void *Thread_Ring_C(void *args)
    {
        pthread_detach(pthread_self());

        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);

        while (true)
        {

            T t;
            {
                Lockguard locks(tp->getlock());

                while (tp->isEmpty()) // 判断环形队列里是否为空
                {
                    tp->Threadwait(); // 弱满足条件就等待
                }
            }
            t(); // 计算任务

            cout << "线程已经处理完成任务：" << t.Printres() << endl;
        }
    }

    void init()
    {
        for (int i = 0; i < _num; i++)
        {
            _threads.push_back(Thread(i, Thread_Ring_C, this));
        }
    }

    void start() // 启动线程
    {
        for (auto &t : _threads)
        {
            t.Running();
        }
    }

    void check()
    {
        for (auto &t : _threads)
        {
            cout << t.threadname() << " running..." << endl;
        }
    }

    void pushTask(const T &t)
    {
        Lockqueue locks(&_lock);
        _tasks.push(t);
        Threadwakeup();
    }

    ~ThreadPool()
    {
        for (auto &t : _threads)
        {
            t.join();
        }
        pthread_mutex_destroy(&_mt);
        pthread_mutex_destroy(&_cd);
    }

private:
    vector<pthread_t> _threads;
    int _num;

    queue<T> _tasks;

    pthread_mutex_t _mt;
    pthread_cond_t _cd;

    static ThreadPool<T> *instance;
    static pthread_mutex_t instance_lock;
};

// 静态初始化
template <class T>
ThreadPool<T> *Threadpool<T>::instance = nullptr;

template <class T>
ThreadPool<T> *Threadpool<T>::instance_lock = PTHREAD_ADAPTIVE_MUTEX_INITIALIZER;
